package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private RedisTemplate redisTemplate;
    @Override
    public Shop queryById(Long id) {
        //从reids缓存中查询数据，如果有直接返回
        Map entries = redisTemplate.opsForHash().entries("shop:" + id);
        if (entries!=null&&!entries.isEmpty()){
            //有数据直接返回
            Shop shop = BeanUtil.fillBeanWithMap(entries, new Shop(), true);
            return shop;
        }
        //如果没有就去查询数据库
        Shop shop = getById(id);
        Map<String, Object> stringObjectMap = BeanUtil.beanToMap(shop);
        redisTemplate.opsForHash().putAll("shop:" + id,stringObjectMap);
        return shop;
    }

    @Transactional
    public void updated(Shop shop) {
        //跟新数据库
       updateById(shop);
        //删除缓存
        redisTemplate.delete("shop:" + shop.getId());
    }
}
